package com.film.dao;

import com.film.entity.CinemaHall;
import com.film.entity.Movie;
import com.film.entity.MovieSession;
import com.film.util.DBTemplate;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HustleLr
 * @version 1.0.0
 * @date 2023/12/13 15:15
 * @describe MovieSession
 */
public class MovieSessionDao extends DBTemplate {
    public List<MovieSession> getMovieHall() {
        String sql = "select session_id,session_time, m.movie_id, ch.hall_id, m.title, ch.`name`,ch.location " +
                "from moviesessions ms " +
                "LEFT JOIN movies m on ms.movie_id=m.movie_id " +
                "LEFT JOIN cinemahalls ch on ms.hall_id=ch.hall_id";
        ;
        return (List<MovieSession>) executeQuery(sql, null);
    }

    @Override
    protected Object processResultSet(ResultSet rs) throws SQLException {
        List<MovieSession> movieSessions = new ArrayList<>();
        while (rs.next()) {
            String sessionId = rs.getString("session_id");
            String movieId = rs.getString("movie_id");
            String title = rs.getString("title");
            String hallId = rs.getString("hall_id");
            LocalDateTime sessionTime = rs.getTimestamp("session_time").toLocalDateTime();
            String name = rs.getString("name");
            String location = rs.getString("location");
            MovieSession movieSession = new MovieSession();
            CinemaHall cinemaHall = new CinemaHall();
            cinemaHall.setHallId(hallId);
            cinemaHall.setName(name);
            cinemaHall.setLocation(location);
            Movie movie = new Movie();
            movie.setMovieId(movieId);
            movie.setTitle(title);
            movieSession.setSessionId(sessionId);
            movieSession.setMovie(movie);
            movieSession.setSessionTime(sessionTime);
            movieSession.setCinemaHall(cinemaHall);
            movieSessions.add(movieSession);
        }
        return movieSessions;
    }

    @Override
    protected PreparedStatement createPreparedStatement(Connection conn, String sql, List<Object> params) throws SQLException {
        PreparedStatement sta = conn.prepareStatement(sql);
        if(null!=params&&!params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                sta.setObject(i + 1, params.get(i));
            }
        }
        return sta;
    }
}
